<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="proId">
        <el-select
          v-model="queryParams.proId"
          placeholder="请选择项目"
          clearable
          filterable
          remote
          :remote-method="getProjectList"
          :loading="projectLoading"
          style="width: 180px;"
        >
          <el-option
            v-for="project in projectList"
            :key="project.id"
            :label="project.proName"
            :value="project.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="机器码" prop="machineId">
        <el-input
          v-model="queryParams.machineId"
          placeholder="请输入机器码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="激活码" prop="activeCode">
        <el-input
          v-model="queryParams.activeCode"
          placeholder="请输入激活码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="激活状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择激活状态" clearable style="width: 150px;">
          <el-option label="未激活" value="0" />
          <el-option label="已激活" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="激活时间" prop="activeTime">
        <el-date-picker clearable
          v-model="queryParams.activeTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择激活时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="过期时间" prop="expireTime">
        <el-date-picker clearable
          v-model="queryParams.expireTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择过期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['machine:activation:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['machine:activation:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['machine:activation:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['machine:activation:export']"
        >导出</el-button>
      </el-col>
      <!-- 生成激活码功能已移除 -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="activationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="项目ID"  width="75" align="center" prop="proId" />
      <el-table-column label="项目名称" align="center" width="150">
        <template #default="scope">
          {{ scope.row.proName || getProjectName(String(scope.row.proId)) }}
        </template>
      </el-table-column>
      <el-table-column label="机器码" align="center" prop="machineId" width="240" />
      <el-table-column label="激活码" align="center" prop="activeCode" width="360" />
      <el-table-column label="当前积分" align="center" prop="currentMark"  width="80"  />
      <el-table-column label="状态" align="center" prop="status"  width="95" >
        <template #default="scope">
          <span :class="{
            'status-disabled': scope.row.status === '3' || scope.row.status === 3,
            'status-expired': scope.row.status === '2' || scope.row.status === 2,
            'status-active': scope.row.status === '1' || scope.row.status === 1,
            'status-inactive': scope.row.status === '0' || scope.row.status === 0
          }">
            {{ getStatusText(scope.row.status) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="激活时间" align="center" prop="activeTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.activeTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="过期时间" align="center" prop="expireTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expireTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="备注" align="center" prop="note" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['machine:activation:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['machine:activation:remove']">删除</el-button>
          <el-button link type="warning" icon="Lock" @click="handleDisable(scope.row)" v-hasPermi="['machine:activation:disable']" v-if="scope.row.status !== '3' && scope.row.status !== 3">禁用</el-button>
          <el-button link type="success" icon="Unlock" @click="handleEnable(scope.row)" v-hasPermi="['machine:activation:enable']" v-if="scope.row.status === '3' || scope.row.status === 3">启用</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改激活电脑对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="activationRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目名称" prop="proId">
          <el-select
            v-model="form.proId"
            placeholder="请选择项目"
            filterable
            remote
            :remote-method="getProjectList"
            :loading="projectLoading"
            style="width: 100%;"
          >
            <el-option
              v-for="project in projectList"
              :key="project.id"
              :label="project.proName"
              :value="project.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="机器码" prop="machineId">
          <el-input v-model="form.machineId" placeholder="请输入机器码" />
        </el-form-item>
        <el-form-item label="激活码" prop="activeCode">
          <el-input v-model="form.activeCode" placeholder="请输入激活码" />
        </el-form-item>
        <el-form-item label="当前积分" prop="currentMark">
          <el-input v-model="form.currentMark" type="number" placeholder="请输入当前积分" />
        </el-form-item>
        <el-form-item label="激活状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择激活状态" style="width: 100%;">
            <el-option label="未激活" value="0" />
            <el-option label="已激活" value="1" />
            <el-option label="已禁用" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="激活时间" prop="activeTime">
          <el-date-picker clearable
            v-model="form.activeTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择激活时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="过期时间" prop="expireTime">
          <el-date-picker clearable
            v-model="form.expireTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择过期时间">
          </el-date-picker>
        </el-form-item>
<!--        <el-form-item label="备注" prop="note">
<!--          <el-input v-model="form.note" type="textarea" placeholder="请输入内容" />
<!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 生成激活码对话框已移除 -->
  </div>
</template>

<script setup name="Activation">
import { listActivation, getActivation, delActivation, addActivation, updateActivation } from "@/api/machine/activation";
import { listProject } from "@/api/project";

const { proxy } = getCurrentInstance();

const activationList = ref([]);
const projectList = ref([]);
const open = ref(false);
// 生成激活码相关变量已移除
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const activeOptions = ref([{ label: '未激活', value: 0 }, { label: '已激活', value: 1 }, { label: '已禁用', value: 3 }]);
const projectLoading = ref(false);

const data = reactive({
  form: {},
  // 生成激活码表单已移除,
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    proId: null,
    machineId: null,
    activeCode: null,
    status: null,
    activeTime: null,
    expireTime: null,
  },
  rules: {
    proId: [
      { required: true, message: "项目不能为空", trigger: "change" }
    ],
    machineId: [
      { required: true, message: "机器码不能为空", trigger: "blur" }
    ],
    activeCode: [
      { required: true, message: "激活码不能为空", trigger: "blur" }
    ],
  },
  // 生成激活码验证规则已移除
});

const { queryParams, form, rules } = toRefs(data);
  
  // 修复修改弹窗中项目名称显示问题 - 在获取数据后设置正确的项目选择

/** 查询激活电脑列表 */
function getList() {
  loading.value = true;
  listActivation(queryParams.value).then(response => {
    activationList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询项目列表 */
function getProjectList() {
  projectLoading.value = true;
  listProject({ pageNum: 1, pageSize: 100 }).then(response => {
    projectList.value = response.rows;
    projectLoading.value = false;
  });
}

/** 根据项目ID获取项目名称 */
function getProjectName(proId) {
  if (!proId) {
    return '';
  }
  const project = projectList.value.find(item => item.id === proId);
  return project ? project.proName : '未知项目';
}

/** 获取状态文本 */
function getStatusText(status) {
  const statusMap = {
    '0': '未激活',
    '1': '已激活',
    '2': '已过期',
    '3': '已禁用'
  };
  // 确保status是字符串类型
  const statusStr = String(status);
  return statusMap[statusStr] || '未知状态';
}

// 取消按钮
function cancel() {
  // 修复弹窗无法关闭的问题
  // 确保表单验证不阻止弹窗关闭
  if (proxy.$refs["activationRef"] && proxy.$refs["activationRef"].clearValidate) {
    proxy.$refs["activationRef"].clearValidate();
  }
  // 确保open值被正确设置为false
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    proId: null,
    machineId: null,
    activeCode: null,
    currentMark: null,
    status: "0", // 默认设置为未激活
    activeTime: null,
    endTime: null,
    note: null
  };
  proxy.resetForm("activationRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  // 获取项目列表和激活码列表
getProjectList();
getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

  // 多选框选中数据
function handleSelectionChange(selection) {
  // 更新选中的ID列表
  ids.value = selection.map(item => item.id);
  
  // 控制修改按钮的禁用状态：仅当选中1项时启用修改按钮
  // 当选择的数量不等于1时，single为true，修改按钮被禁用
  single.value = selection.length !== 1;
  
  // 控制删除按钮的禁用状态：当选中至少1项时启用删除按钮
  // 当选择的数量等于0时，multiple为true，删除按钮被禁用
  multiple.value = selection.length === 0;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加激活电脑";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  // 先确保项目列表已加载
  const loadProjects = projectList.value.length === 0 ? getProjectList() : Promise.resolve();
  
  loadProjects.then(() => {
    getActivation(_id).then(response => {
      // 确保status字段是字符串类型，以匹配el-select组件的选项值
      const data = response.data;
      if (data.status !== undefined) {
        data.status = String(data.status);
      }
      
      // 确保proId是字符串类型以匹配下拉选项
      if (data.proId !== undefined) {
        data.proId = String(data.proId);
      }
      
      form.value = data;
      open.value = true;
      title.value = "修改激活电脑";
    });
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["activationRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateActivation(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          // 获取项目列表和激活码列表
getProjectList();
getList();
        });
      } else {
        addActivation(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          // 获取项目列表和激活码列表
getProjectList();
getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除激活电脑编号为"' + _ids + '"的数据项？').then(function() {
    return delActivation(_ids);
  }).then(() => {
    // 获取项目列表和激活码列表
getProjectList();
getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}



/** 导出按钮操作 */
function handleExport() {
  proxy.download('machine/code/export', {
    ...queryParams.value
  }, `activation_${new Date().getTime()}.xlsx`)
}

/** 禁用激活码 */
function handleDisable(row) {
  const id = row.id;
  proxy.$modal.confirm('是否确认禁用激活码？', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(function() {
    // 创建一个禁用状态的更新对象
    const updateData = {
      id: id,
      status: '3' // 3表示已禁用
    };
    return updateActivation(updateData);
  }).then(() => {
    getProjectList();
getList();
    proxy.$modal.msgSuccess("禁用成功");
  }).catch(() => {});
}

/** 启用激活码 */
function handleEnable(row) {
  const id = row.id;
  proxy.$modal.confirm('是否确认启用激活码？', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(function() {
    // 创建一个启用状态的更新对象
    const updateData = {
      id: id,
      status: '1' // 1表示已激活
    };
    return updateActivation(updateData);
  }).then(() => {
    getProjectList();
getList();
    proxy.$modal.msgSuccess("启用成功");
  }).catch(() => {});
}

// 获取项目列表和激活码列表
getProjectList();
getList();
</script>

<style scoped>
/* 状态样式 */
.status-disabled {
  color: #909399;
  background-color: #f5f7fa;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-expired {
  color: #e6a23c;
  background-color: #fdf6ec;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-active {
  color: #67c23a;
  background-color: #f0f9eb;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-inactive {
  color: #606266;
  background-color: #f5f7fa;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}
</style>
